package services

import (
	"errors"
	"rustdesk_api_server/repository"
	"rustdesk_api_server/utils"
	"time"

	"gorm.io/gorm"
)

var Auth = new(AuthService)

type AuthService struct{}

func (auth *AuthService) UserLogin(username, password, clientId, uuid, ip string) (string, error) {
	user, err := repository.Users.GetUserByUsername(username)
	if err == gorm.ErrRecordNotFound {
		return "", errors.New("用户不存在")
	}
	if ok := utils.ComparePassword(user.Password, password); !ok {
		return "", errors.New("用户密码错误")
	}
	user.LastLoginTime = time.Now()
	user.LastLoginIP = ip
	err = repository.Users.Update(user)
	if err != nil {
		return "", err
	}

	token, err := utils.GenerateToken(int(user.ID), user.Username, clientId, uuid)
	return token, err
}
